package com.heima.gateway.filter;


import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Service
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //获取请求url
        String url = request.getURI().getPath();
        //如果请求url中包含/login直接放行
        if (url.contains("/login")) {
            return chain.filter(exchange);
        }
        //不包含“/login”需要拦截获取请求头
        String token = request.getHeaders().getFirst("token");

        //判断请求头token中是否有token
        //没有token，返回401（未授权状态码）
        if (StringUtils.isEmpty(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //有token，通过JWT校验token是否有效
        try {
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int result = AppJwtUtil.verifyToken(claims);
            if (result == -1 || result == 0) {
                Object userId = claims.get("userId");
                Object name = claims.get("name");
                request.mutate().header("userId",userId.toString());
                request.mutate().header("name",name.toString());
                return chain.filter(exchange);
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }
        //其他异常，统一返回401
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
